//index.js
//获取应用实例
const app = getApp();
let wxCharts = require('../../utils/wxcharts.js');
let tool = require('../../utils/tool.js');
const httpUtils = require('../../utils/httpUtils.js');

Page({
  data: {
    year: 0, //付息日历开始
    month: 0,
    week: ['日', '一', '二', '三', '四', '五', '六'],
    dateArr: [],
    isToday: 0,
    isTodayWeek: false,
    todayIndex: 0,
    confirmles: ['201957', '201958'], //審核中的申請
    confirmed: ['201955', '201956'], //审核通过的申请
    justsub: [], //仅仅提交了的约课
    yuekearr: [],
    date: '2019-01-01 00:00',
    disabled: false, //设置是否能点击 false可以 true不能点击复习日历结束
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    imageurl: 'https://yxpmaterial.oss-cn-beijing.aliyuncs.com/',
    videoUrl: "https://yxpmaterial.oss-cn-beijing.aliyuncs.com/9a5a26bdceba4668210d94489abe27a8.mp4",
    maskDis: "none",
    riliDis: "none",
    jbDis: "none",
    swiperdis: "block",
    chart1data: {},
    chart2data: {},
    chart3data: {},
    chart4data: {},
    chart5data: {},
    linkArr: {},
    swiper2Dis: 'none',
    mobile: false,
    isVip: false,
    is_show: 1,
    is_word_study: 0,      //是否显示 自主单词学习功能，tag学习渠道：0：在校陪练，为0的时候隐藏；1：在家自反馈；2：远程一对一，弹输入code窗；
    is_org_canstudy: 0,//0不显示 1显示
    is_essay_homework: 0, //id 为0的时候没有作文仿写作业，其他的时候为文章id
    showVIPDis: "none",//开通会员弹窗是否弹出
    dialogDis: "none",
    inputCode: "",//输入的code
    inputValue: "",//输入的值
    is_show_profit:0, //是否显示领取公益课的按钮
  },
  //事件处理函数
  bindViewTap: function () {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function () {
    this.setData({
      studentInfo: app.globalData.studentInfo
     })
  },
  getUserInfo: function (e) {
    app.globalData.userInfo = e.detail.userInfo

    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  onShow: function () {
    this.setData({
      mobile: app.globalData.studentInfo.mobile,
    });
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    }

    // else {
    //   // 在没有 open-type=getUserInfo 版本的兼容处理
    //   wx.getUserInfo({
    //     success: res => {
    //       app.globalData.userInfo = res.userInfo
    //       this.setData({
    //         userInfo: res.userInfo,
    //         hasUserInfo: true
    //       })
    //     }
    //   })
    // }

    this.getData(); //图表数据

    //加载日历
    this.nowdata();
  },

  //点击领取公益课
  getPublicCourse: function () {
    console.log("------点击领取----")
    let that = this;
    wx.showLoading({
      title: '正在加载',
      mask: true
    })
    httpUtils.getPublicCourse({
      id: app.globalData.studentInfo.id,
    }).then((res) => {
      console.log(res.data.message)
      wx.showModal({
        title: '温馨提示',
        content: res.data.message,
        showCancel: false,
      });
    });
  },

  createSimulationData: function () {
    var categories = [];
    var data = [];
    for (var i = 0; i < 10; i++) {
      categories.push((i + 1));
      data.push(Math.random() * (20 - 10) + 10);
    }
    // data[4] = null;
    return {
      categories: categories,
      data: data
    }

  },

  gotourl: (e) => {
    wx.navigateTo({
      url: e.currentTarget.dataset.urldata,
    });
  },
  switchRili: function (e) {
    this.getCardData();
    this.setData({
      maskDis: e.currentTarget.dataset.masksw
    });
    this.setData({
      riliDis: e.currentTarget.dataset.masksw
    });
    if (this.data.riliDis == 'none') {
      this.setData({
        swiperdis: 'block'
      })
    } else {
      this.setData({
        swiperdis: 'none'
      })
    }
  },
  switchMask: function (e) {
    this.setData({
      maskDis: e.currentTarget.dataset.masksw,
      jbDis: e.currentTarget.dataset.masksw
    });
    if (this.data.jbDis == 'none') {
      this.setData({
        swiperdis: 'block'
      })
    } else {
      this.setData({
        swiperdis: 'none'
      })
    }
  },
  nowdata: function () { //复习日历开始
    let now = new Date();
    let year = now.getFullYear();
    let month = now.getMonth() + 1;
    this.dateInit();
    this.setData({
      year: year,
      month: month,
      isToday: '' + year + month + now.getDate()
    })
  },
  dateInit: function (setYear, setMonth) {
    //全部时间的月份都是按0~11基准，显示月份才+1
    let dateArr = []; //需要遍历的日历数组数据
    let arrLen = 0; //dateArr的数组长度
    let now = setYear ? new Date(setYear, setMonth) : new Date();
    let year = setYear || now.getFullYear();
    let nextYear = 0;
    let month = setMonth || now.getMonth(); //没有+1方便后面计算当月总天数
    let nextMonth = (month + 1) > 11 ? 1 : (month + 1);
    let startWeek = new Date(year + '/' + (month + 1) + '/' + 1).getDay(); //目标月1号对应的星期
    let dayNums = new Date(year, nextMonth, 0).getDate(); //获取目标月有多少天
    let obj = {};
    let num = 0;
    //设置timepicker的年份范围
    this.setData({
      startDate: year,
      endDate: year + 1
    });
    if (month + 1 > 11) {
      nextYear = year + 1;
      dayNums = new Date(nextYear, nextMonth, 0).getDate();
    }
    arrLen = startWeek + dayNums;
    for (let i = 0; i < arrLen; i++) {
      if (i >= startWeek) {
        num = i - startWeek + 1;
        obj = {
          isToday: '' + year + (month + 1) + num,
          // formateDate: '' + year + '/' + (month > month ? month + 1 : '0' + (month + 1)) + '/' + (num < 10 ? '0' + num : num),
          formateDate: '' + year + '/' + (month >= 9 ? month + 1 : '0' + (month + 1)) + '/' + (num < 10 ? '0' + num : num),
          dateNum: num,
          weight: 5
        }
      } else {
        obj = {};
      }
      dateArr[i] = obj;
    }
    this.setData({
      dateArr: dateArr
    })

    let nowDate = new Date();
    let nowYear = nowDate.getFullYear();
    let nowMonth = nowDate.getMonth() + 1;
    let nowWeek = nowDate.getDay();
    let getYear = setYear || nowYear;
    let getMonth = setMonth >= 0 ? (setMonth + 1) : nowMonth;

    if (nowYear == getYear && nowMonth == getMonth) {
      this.setData({
        isTodayWeek: true,
        todayIndex: nowWeek
      })
    } else {
      this.setData({
        isTodayWeek: false,
        todayIndex: -1
      })
    }
  },
  lastMonth: function () {
    //全部时间的月份都是按0~11基准，显示月份才+1
    let year = this.data.month - 2 < 0 ? this.data.year - 1 : this.data.year;
    let month = this.data.month - 2 < 0 ? 11 : this.data.month - 2;
    this.setData({
      year: year,
      month: (month + 1)
    })
    this.dateInit(year, month);
    this.getCardData();
  },
  nextMonth: function () {
    //全部时间的月份都是按0~11基准，显示月份才+1
    let year = this.data.month > 11 ? this.data.year + 1 : this.data.year;
    let month = this.data.month > 11 ? 0 : this.data.month;
    this.setData({
      year: year,
      month: (month + 1)
    })
    this.dateInit(year, month);
    this.getCardData();
  },
  closeRili: function () {
    this.setData({
      maskDis: "none",
      riliDis: "none",
      swiperdis: 'block'
    })
  } //复习日历结束
  ,
  //外連接
  outLlik: function (e) {
    app.globalData.outUrl = e.currentTarget.dataset.outurl;
    if (!e.currentTarget.dataset.outurl) {
      return;
    }
    wx.navigateTo({
      url: '../outLink/outLink',
    })
  },



  //获取首页数据，并设置折线图
  getData: function () {
    let that = this;
    //获取主页折线图的数据
    let paramArr = {
      access_token: app.globalData.studentInfo.access_token
    }
    let rs = tool.getSign(paramArr, app.globalData.key); //返回 bodyParam heaer sign
    let sign = rs.sign;
    let apiUrl = app.globalData.apiURL + "user/index?sign=" + sign;
    let chartPro = new Promise(
      function (resolve, reject) {
        wx.request({
          url: apiUrl,
          header: rs.header,
          data: rs.bodyParam,
          method: 'post',
          success(res) {
            resolve(res);
          }
        })
      }

    );

    chartPro.then(function (rs) {
      if (rs.data.code == 1) {
        let datas = rs.data;

        // is_essay_homework: datas.data.is_essay_homework,
        that.setData({
          chart1data: datas.data.statics_list[0],
          chart2data: datas.data.statics_list[1],
          chart3data: datas.data.statics_list[2],
          chart4data: datas.data.statics_list[3],
          chart5data: datas.data.statics_list[4], 
          is_show: datas.data.is_show,
          is_word_study: datas.data.tag,  
          is_org_canstudy:datas.data.org_canstudy, 
          is_show_profit:datas.data.is_show_profit,
          isVip: (datas.data.vip == 1 ? true : false)
        })

        if (datas.data.parent_read.length > 0) {
          that.setData({
            linkArr: datas.data.parent_read,
            swiper2Dis: "block"
          });
        }
        var windowWidth = 320;
        var res = wx.getSystemInfoSync();
        if (res.windowWidth) {
          windowWidth = res.windowWidth;
        } else {
          windowWidth = res.screenWidth;
        }
        var simulationData = that.createSimulationData();
        let lineChart = new Array();
        for (let i = 0; i < 5; i++) {
          let categories = [];
          let seris1 = [];
          let seris2 = [];
          let seris3 = [];
          let ymax = 0;

          switch (i) {
            case 0:
              categories = that.data.chart1data.statics.day;
              seris1 = (that.data.chart1data.statics.study);
              seris2 = (that.data.chart1data.statics.review);
              ymax = [Math.max(...seris1) > Math.max(...seris2) ? Math.max(...seris1) : Math.max(...seris2)];
              // ymax = seris1.sort().slice(seris1.length - 1) > seris2.sort().slice(seris2.length - 1) ? seris1.sort().slice(seris1.length - 1) : seris2.sort().slice(seris2.length - 1);

              break;
            case 1:
              if (that.data.chart2data.statics.day.length === 0) {
                break;
              }
              categories = that.data.chart2data.statics.day;
              seris1 = that.data.chart2data.statics.num;
              ymax = [Math.max(...seris1)];
              // ymax = seris1.sort().slice(seris1.length - 1)

              break;
            case 2:
              if (that.data.chart3data.statics.day.length == 0) {
                break;
              }
              categories = that.data.chart3data.statics.day;
              seris1 = that.data.chart3data.statics.num;
              ymax = [Math.max(...seris1)];
              // ymax = seris1.sort().slice(seris1.length - 1)
              break;
            case 3:
              if (that.data.chart4data.statics.day.length == 0) {
                break;
              }
              categories = that.data.chart4data.statics.day;
              seris1 = that.data.chart4data.statics.study;
              seris2 = that.data.chart4data.statics.review;
              ymax = [Math.max(...seris1)];
              break;
            case 4:
              if (that.data.chart5data.statics.day.length == 0) {
                break;
              }
              categories = that.data.chart5data.statics.day;
              seris1 = (that.data.chart5data.statics.essay);
              ymax = [Math.max(...seris1)];
              // seris2 = (that.data.chart5data.statics.phrase);
              // seris3 = (that.data.chart5data.statics.sentence);
              // let temp = [Math.max(...seris1) > Math.max(...seris2) ? Math.max(...seris1) : Math.max(...seris2)];
              // ymax = [temp > Math.max(...seris3) ? temp : Math.max(...seris3)];
              break;
            default:
              break;
          }
          for (let ele in categories) {
            categories[ele] = categories[ele].slice(5);
          }

          if (i == 0) {
            lineChart[i] = new wxCharts({
              canvasId: 'lineCanvas' + i.toString(),
              type: 'line',
              categories: categories,
              animation: true,
              series: [{
                name: '成交量' + i,
                data: seris1,
                format: function (val, name) {
                  // return val.toFixed(0);
                  return parseInt(val).toFixed();
                }
              }, {
                name: '成交量2',
                data: seris2,
                format: function (val, name) {
                  // return val.toFixed(0);
                  return parseInt(val).toFixed();
                }
              }],
              xAxis: {
                disableGrid: true
              },
              yAxis: {
                title: '',
                format: function (val) {
                  // return val.toFixed(0);
                  return parseInt(val).toFixed();
                },
                min: 0,
                max: ymax[0] + 5,
              },
              width: windowWidth - 50,
              height: windowWidth / 3,
              dataLabel: true,
              dataPointShape: false,
              legend: false,
              extra: {
                lineStyle: 'line'
              }
            });
          } else if (i == 3) {
            if (seris1.length > 0) {
              lineChart[i] = new wxCharts({
                canvasId: 'lineCanvas' + i.toString(),
                type: 'line',
                categories: categories,
                animation: true,
                series: [{
                  name: '成交量' + i,
                  data: seris1,
                  format: function (val, name) {
                    // return val.toFixed(0);
                    return parseInt(val).toFixed();
                  }
                }, {
                  name: '成交量2',
                  data: seris2,
                  format: function (val, name) {
                    // return val.toFixed(0);
                    return parseInt(val).toFixed();
                  }
                }],
                xAxis: {
                  disableGrid: true
                },
                yAxis: {
                  title: '',
                  format: function (val) {
                    // return val.toFixed(0);
                    return parseInt(val).toFixed();
                  },
                  min: 0,
                  max: ymax[0] + 5,
                },
                width: windowWidth - 50,
                height: windowWidth / 3,
                dataLabel: true,
                dataPointShape: false,
                legend: false,
                extra: {
                  lineStyle: 'line'
                }
              });
            }
          } else {
            if (seris1.length > 0) {
              lineChart[i] = new wxCharts({
                canvasId: 'lineCanvas' + i.toString(),
                type: 'line',
                categories: categories,
                animation: true,
                series: [{
                  name: '成交量' + i,
                  data: seris1,
                  format: function (val, name) {
                    return val.toFixed(0);
                  }
                }],
                xAxis: {
                  disableGrid: true
                },
                yAxis: {
                  title: '',
                  format: function (val) {
                    return val.toFixed(0);
                  },
                  min: 0,
                  max: ymax[0] + 5,
                },
                width: windowWidth - 50,
                height: windowWidth / 3,
                dataLabel: true,
                dataPointShape: false,
                legend: false,
                extra: {
                  lineStyle: 'line'
                }
              });
            }

          }

        }

      } else if (rs.data.code == 10001) {
        wx.redirectTo({
          url: '/pages/login/login',
        })
      } else {
        wx.showToast({
          title: rs.data.info,
        })
      }
    })
  },

  //获取打卡数据
  getCardData: function () {
    let that = this;
    let date = that.data.year + '-' + (that.data.month > 9 ? that.data.month : "0" + that.data.month.toString());
    let paramArr = {
      access_token: app.globalData.studentInfo.access_token,
      date: date,
    }
    let rs = tool.getSign(paramArr, app.globalData.key); //返回 bodyParam heaer sign
    let sign = rs.sign;
    let apiUrl = app.globalData.apiURL + "user/reviewclock?sign=" + sign;
    let cardPro = new Promise(
      function (resolve, reject) {
        wx.request({
          url: apiUrl,
          header: rs.header,
          data: rs.bodyParam,
          method: 'post',
          success(res) {
            resolve(res);
          }
        })
      }
    );
    cardPro.then(function (rs) {
      if (rs.data.code == 1) {
        let classHis = rs.data;
        that.setData({
          confirmed: classHis.data.review,
          confirmles: classHis.data.study,
          justsub: classHis.data.notreview
        });
      } else if (rs.data.code == 10001) {
        wx.redirectTo({
          url: '/pages/login/login',
        })
      }
    })
  }, //评价老师
  gotoAccess: function () {
    wx.navigateTo({
      url: '../assessTeacher/assessList/assessList',
    })
  },
  goPay: function () {
    wx.navigateTo({
      url: '/pages/vip/vipBuy',
    })
  },

  /**
   * 点击自主学习按钮（单词学习入口）
   */
  gotoWordStudy: function (e) {
    let that = this;
    // if (that.data.isVip === false) {
    //   //如果不是会员，点击弹开通vip的弹窗
    //   this.setData({
    //     maskDis: e.currentTarget.dataset.masksw,
    //     showVIPDis: e.currentTarget.dataset.masksw
    //   });

    //   if (this.data.showVIPDis == 'none') {
    //       this.setData({
    //         swiperdis: 'block'
    //       })
    //     } else {
    //       this.setData({
    //         swiperdis: 'none'
    //       })
    //     }

    // }else{
      //如果是会员，则去判断学习渠道
      if (this.data.is_word_study == 2) {
  
        this.setData({
          maskDis: e.currentTarget.dataset.masksw
        });
        this.setData({
          dialogDis: e.currentTarget.dataset.masksw
        });
        if (this.data.dialogDis == 'none') {
          this.setData({
            swiperdis: 'block'
          })
        } else {
          this.setData({
            swiperdis: 'none'
          })
        }
      } else {
        wx.navigateTo({
          url: '/pages/studyWord/ninebox/ninebox',
        })
      }

    // }
  },




  /**点击弹窗里的按钮，解除绑定 */
  cleanRelation: function () {
    let that = this;
    let paramArr = {
      access_token: app.globalData.studentInfo.access_token,
      openid: app.globalData.studentInfo.openid,
    }
    let rs = tool.getSign(paramArr, app.globalData.key); //返回 bodyParam heaer sign
    let sign = rs.sign;
    let apiUrl = app.globalData.apiURL + "user/unbind?sign=" + sign;
    let cardPro = new Promise(
      function (resolve, reject) {
        wx.request({
          url: apiUrl,
          header: rs.header,
          data: rs.bodyParam,
          method: 'post',
          success(res) {
            if (res.data.code === 1) {
              wx.showToast({
                title: res.data.info,
              })
              setTimeout(function () {
                wx.redirectTo({
                  url: '/pages/login/login',
                }), 1000
              })
            } else if (res.data.code == 10001) {
              wx.redirectTo({
                url: '/pages/login/login',
              })
            } else {
              wx.showToast({
                title: res.data.info,
              })
              setTimeout(function () {
                wx.redirectTo({
                  url: '/pages/login/login',
                }), 1000
              })
            }
          }
        })
      }
    );
  },
  /**
   * 输入code框的输入框的监听
   */
  codeInput: function (event) {
    // console.log(event);
    let code = event.detail.value;
    this.setData({
      inputCode: code,
    })
  },
  /**
 * 输入code框的点叉号关闭对话框
 */
  closeDialog: function () {
    this.setData({
      dialogDis: "none",
      maskDis: "none",
      swiperdis: 'block'
    })
  },
  /**
   * 输入code框的确定按钮  开始验证code码
   */
  clickDialogSure: function () {
    if (this.data.inputCode != "") {
      this.getCheckTag();
    }

  },
  preventTouchMove: function () {

  },
  //根据code获取学习渠道
  getCheckTag: function () {
    let that = this;
    wx.showLoading({
      title: '',
      mask: true
    })
    httpUtils.getCheckTag({
      access_token: app.globalData.studentInfo.access_token ? app.globalData.studentInfo.access_token : app.globalData.access_token,
      code: this.data.inputCode,
      openid: app.globalData.studentInfo.openid,
    }).then((res) => {
      console.log(res);
      if (res.data.type == 1) {
        this.setData({
          dialogDis: "none",
          maskDis: "none",
          swiperdis: 'block',
          inputValue: "",
        })
        wx.navigateTo({
          url: '/pages/studyWord/ninebox/ninebox',
        })
      } else {
        wx.showToast({
          title: res.data.message,
          icon: 'none',
          duration: 2000
        });
        // this.setData({
        //   inputValue: "",
        // })

      }


    });
  },

  // 开通会员
  govip: function(e) {
    this.setData({
      showVIPDis: "none",
      maskDis: "none",
      swiperdis: 'block'
    })
    wx.navigateTo({
      url: e.currentTarget.dataset.urldata,
    });
  },

  closeVipMask: function() {
    this.setData({
      showVIPDis: "none",
      maskDis: "none",
      swiperdis: 'block'
    })
   
  },
})